package com.cqs.learning.classload;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author lixiaowen
 * @date 2019/9/20
 */
public class MyClassLoader extends ClassLoader {


    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        String fileName =  "/" + name.replaceAll("\\.","/") + ".class";
        InputStream is = getClass().getResourceAsStream(fileName);
        if (name.startsWith("java")) {
            is = null;
        }
        if (is == null) {
//            System.out.println(fileName + " resource as stream is null ");
            return super.loadClass(name);
        }
        byte[] bs = new byte[0];
        try {
            bs = new byte[is.available()];
            is.read(bs);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return defineClass(name,bs, 0 , bs.length);
    }
}
